package com.baymax.test.scene.internal

import android.content.Context
import android.graphics.Matrix
import android.graphics.Rect
import android.graphics.RectF
import android.util.Log
import android.view.View
import androidx.core.graphics.toRect
import androidx.core.graphics.toRectF
import kotlin.math.ceil

/**
 * @author L14
 */
class ItemsSizeLookup(context: Context, private val styles: () -> List<Style>) : ChildSizeLookup {

    private val matrix = Matrix()
    val rectF = RectF()
    private val BASE_WIDTH = 1920f
    private var scaleFactor = 0f

    init {
        if (scaleFactor <= 0f) {
            scaleFactor = context.resources.displayMetrics.widthPixels / BASE_WIDTH
        }
        println(this)
    }

    override fun getSize(child: View, position: Int, size: Rect) {
        styles().getOrNull(position)?.let { item ->
            item.fitRect(rectF)
            matrix.setScale(scaleFactor, scaleFactor)
            matrix.mapRect(rectF)
            rectF.round(size)
            Log.d("aaa", "rect:$rectF: $size $item")
        }
    }

    override fun scaleFactor(): Float {
        return scaleFactor
    }

    override fun toString(): String {
        return "ItemsSizeLookup(scaleFactor=$scaleFactor)"
    }

    override fun totalHeight(): Int {
        return ((styles().maxOf { it.renderHeight } + styles().maxOf { it.top } ) * scaleFactor + 0.5).toInt()
    }

    private fun RectF.setRect(rect: Rect) {
        rect.set(
            (left + 0.5f).toInt(),
            (top + 0.5f).toInt(),
            (right + 0.5f).toInt(),
            (bottom + 0.5f).toInt()
        )
    }
}